<template>
  <view class="preview">
    <!-- 填写订单 -->
    <!-- 收货人 -->
    <view class="receiver" @tap="chooseReceiver">
      <AddressInfoComp :receiver="state.order.receiver"/>
    </view>
    <!-- 商品信息 -->
    <view class="products">
      <scroll-view scroll-y :style="{height: (windowHeight - 44 - 58 - 120 - 50 - 20) + 'px'}">
        <ProductInfoComp :products="state.order.products"/>
      </scroll-view>
    </view>
    <!-- 结算信息 -->
    <view class="bill">
      <BillInfoComp :bill="state.order.bill"/>
    </view>
    <view class="btn-grp">
      <view class="btn-item uni-mr-10">
        <button size="mini" @tap="cancelOrder">取消</button>
      </view>
      <view class="btn-item uni-mr-10">
        <button type="warn" size="mini" @tap="submitOrder">提交订单</button>
      </view>
    </view>
    <!-- 增加一个弹出层 -->
    <uni-popup ref="popupRef" background-color="#fff" type="bottom">
      <view class="receiver-list">
        <AddressPanel :address-list="state.addressList" @return-addr-event="handleReceiveAddr"/>
      </view>
    </uni-popup>
  </view>
</template>
<script setup lang="ts">
import AddressInfoComp from "@/pagesOrder/settings/components/AddressInfoComp.vue";
import ProductInfoComp from '@/pagesOrder/settings/components/ProductsInfoComp.vue'
import BillInfoComp from '@/pagesOrder/settings/components/BillInfoComp.vue'
import AddressPanel from "@/components/address/AddressPanel.vue";
import {ref} from "vue";
import type {IOrderDetail, IOrderProductItem, OrderFormType} from "@/types/order";
import type {AddressItemType} from "@/types/user";
import {onLoad} from "@dcloudio/uni-app";
import type {ProductItemBriefType} from "@/types/product";
import {getAddressListData, getDefaultAddress} from "@/services/address";
import {calculateBillAmount, createOrder} from "@/services/order";
import type {PageQueryType} from "@/types/global";
import {ORDER_PREVIEW_PRODUCTS, ORDER_SOURCE} from "@/constants/storageConstants";

const {windowHeight} = uni.getSystemInfoSync()

const popupRef = ref()
const state = ref({
  order: {
    receiver: {},
    products: [] as Array<ProductItemBriefType>,
    bill: {}
  } as IOrderDetail,
  orderSource: "", // 下单来源，购物车、商详
  addressList: [] as Array<AddressItemType>,
  query: {
    page: {
      page: 1,
      size: 10,
      orders: []
    } as PageQueryType
  }
})

const chooseReceiver = () => {
  popupRef.value.open()
}

const handleReceiveAddr = (id: number) => {
  console.log("selected addr id: ", id)
  const matchedAddrList = state.value.addressList.filter(addrItem => {
    console.log("local addr: ", addrItem, typeof addrItem.id, typeof id)
    return addrItem.id === id;
  })
  console.log("matched addr: ", matchedAddrList)
  if (matchedAddrList.length <= 0) {
    return
  }
  state.value.order.receiver = matchedAddrList[0]
  popupRef.value.close()
}

const cancelOrder = () => {

}

const submitOrder = () => {
  // 创建订单
  createOrder(assembleOrderForm()).then((r) => {
    if (r.code === 0) {
      // 根据返回的订单编号进入支付页
      // 跳转到支付页
      uni.navigateTo({
        url: "/pagesOrder/settings/pay?number="+r.data
      })
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  }).catch(() => {})
}

const loadStorageProducts = () => {
  const selectedShopcarProductsJsonStr = uni.getStorageSync(ORDER_PREVIEW_PRODUCTS)
  if (selectedShopcarProductsJsonStr) {
    state.value.order.products = JSON.parse(selectedShopcarProductsJsonStr)
    state.value.orderSource = uni.getStorageSync(ORDER_SOURCE)
    console.log("@load order products: ", state.value.order.products)
  } else {
    uni.showToast({
      title: "服务错误，请稍后再试",
      icon: "none"
    })
  }
}

/**
 * 计算账单
 */
const bill = async () => {
  // 提取订单商品的sku id
  await calculateBillAmount(assembleOrderForm()).then((r) => {
    if (r.code === 0) {
      state.value.order.bill = r.data
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  }).catch(() => {})
}

const assembleOrderForm = (): OrderFormType => {
  let orderForm = {} as OrderFormType
  let orderProducts = [] as IOrderProductItem[]
  state.value.order.products.forEach((v) => {
    orderProducts.push({
      id: v.id,
      skuId: v.skuId,
      count: <number>v.count
    })
  })
  orderForm.products = orderProducts
  orderForm.addrId = state.value.order.receiver.id
  orderForm.source = state.value.orderSource
  return orderForm
}
/**
 * 获取默认会使用的收货地址
 */
const getDefaultAddressData = async () => {
  await getDefaultAddress().then((r) => {
    state.value.order.receiver = r.data
  })
}

const getAddressData = () => {
  getAddressListData(state.value.query.page).then((r) => {
    state.value.addressList.push(...r.data.list)
  })
}
onLoad(() => {
  // 从localstorage中读取要结算的商品数据
  // 加载数据
  loadStorageProducts()
  Promise.all([
    getDefaultAddressData(),
    bill()
  ])
  getAddressData()
})
</script>
<style lang="scss">
.preview {
  .receiver {
    height: 50px;
    margin-bottom: 20px;
  }

  .bill {
    height: 120px;
  }

  .btn-grp {
    height: 50px;
    background-color: #fff;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .btn-item {
    }
  }

  .receiver-list {
    height: 350px;
  }
}
</style>